<template>
  <div style="padding: 15px;">
    <el-form ref="form" :rules="rules" :model="form" label-width="80px">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="收货单号">
              <el-input v-model="form.code" style="width:75%"  :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="所属仓库" prop="warehouseCode">
              <el-select v-model="form.warehouseCode" placeholder="请输入所属仓库  " style="width:75%" :disabled="true">
                <el-option
                  v-for="item in warehouseData"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="入驻商" prop="shipmentCode" label-width="100px">
              <el-input v-model="form.shipmentName" style="width:75%"  :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row v-if="isShow0">
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="订单类型">
              <el-input v-model="typeName" style="width:75%"  :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>

        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="供应商" >
              <!-- <supplierSelect ref="supplierSelect"  @setsupplierCode="setsupplierCode" style="width: 75%"/> -->
              <el-input v-model="form.supplierName" style="width:75%" :disabled="true" />

            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="计划到货日期" label-width="100px" >
              <el-input v-model="form.gmtPlanArrival" style="width:75%"  :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row v-if="isShow1">
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="订单类型">
              <el-input v-model="typeName" style="width:75%"  :disabled="true" />
            </el-form-item>
          </div>
        </el-col>

        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="客户">
              <el-input v-model="form.customerName" style="width:75%"  :disabled="true"/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="19">
          <div class="grid-content bg-purple">
            <el-form-item  label="备注">
              <el-input v-model="form.remarks" style="width:75%"  />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <vxe-table
      border
      resizable
      show-overflow
      ref="xTable"
      :align="allAlign"
      :data="tableData"
      show-footer
      :footer-method="footerMethod"
      :edit-rules="validRules"
      :span-method="objectSpanMethod"
      :edit-config="{trigger: 'click', mode: 'cell'}">
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <!-- <vxe-table-column field="receiveCode" title="" width="0" ></vxe-table-column> -->
      <vxe-table-column field="goodsName" title="商品名称" width="270"></vxe-table-column>
      <vxe-table-column field="goodCode" title="商品编码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsBarCode" title="商品条码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsUnitName" title="单位" width="270"></vxe-table-column>
      <vxe-table-column field="planQuantity" title="计划数量"  width="120"></vxe-table-column>
      <vxe-table-column field="receivedQuantity" title="收货数量" width="270" :formatter="formatterReceivedQuantity"></vxe-table-column>
      <vxe-table-column field="cancelQuantity" title="取消数量" :edit-render="{name: 'input', immediate: true, attrs: {type: 'number',min :0}}" width="170" ></vxe-table-column>
      <vxe-table-column field="containerBarCode" title="容器号"  width="120" ></vxe-table-column>
      <vxe-table-column field="goodsStatusName" title="货品状态" width="120" ></vxe-table-column>
      <vxe-table-column field="gmtManufacture" title="生产日期" width="120"></vxe-table-column>
      <vxe-table-column field="gmtExpire" title="过期日期" width="120"></vxe-table-column>
      <vxe-table-column field="receiveLot" title="收货批次" width="120"></vxe-table-column>
      <vxe-table-column field="putawayCode" title="上架单号" width="120"></vxe-table-column>
      <vxe-table-column field="supplier" title="供应商" width="120"></vxe-table-column>
      <vxe-table-column field="serialNumber" title="序列号" width="120"></vxe-table-column>

      <vxe-table-column field="taskCode" title="任务号" width="120"></vxe-table-column>
      <vxe-table-column field="operatorName" title="作业人" width="120"></vxe-table-column>

      <vxe-table-column field="extendOne" title="生产批号" width="120"></vxe-table-column>
      <vxe-table-column field="extendTwo" title="商品批次" width="120"></vxe-table-column>
      <vxe-table-column field="extendThree" title="扩展3" width="120"></vxe-table-column>
      <vxe-table-column field="extendFour" title="扩展4" width="120"></vxe-table-column>
      <vxe-table-column field="extendFive" title="扩展5" width="120"></vxe-table-column>
      <vxe-table-column field="extendSix" title="扩展6" width="120"></vxe-table-column>
      <vxe-table-column field="remarks" title="备注"  width="270"></vxe-table-column>
    </vxe-table>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="funcSubmitCheck" :disabled="isDisable" plain>确认取消</el-button>
    </div>
  </div>
</template>
<script>
  import Vue from 'vue'
  import 'xe-utils'
  import VXETable from 'vxe-table'
  import 'vxe-table/lib/index.css'
  import XEUtils from 'xe-utils'
  import VXEUtils from 'vxe-utils'
  import VXETablePluginElement from 'vxe-table-plugin-element'
  import 'vxe-table-plugin-element/dist/style.css'
  import '@/assets/iconfont/iconfont.css';

  import goodsSelect from '@/views/components/goodsElSelect.vue'
  import {getWarehouse} from '@/api/basicInfo'
  import { goodsUnitConversion, receiveCheckSubmit ,receive, getReceiveRegister} from '@/api/inStorage'
  import shipmentSelect from '@/views/components/shipmentSelect.vue'
  import {  receiveCheckIn, finishReceive} from '@/api/inStorage'
  import supplierSelect from '@/views/components/supplierElSelect.vue'
  Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
  VXETable.use(VXETablePluginElement)
  export default {
    name: 'Parent',
    components: {
      goodsSelect,
      shipmentSelect,
      supplierSelect,
    },
    data() {
      return {
        allAlign:'center',
        warehouseData:[],
        units:[],
        modelEditFlag: false,
        isShow0:false,
        isShow1:false,
      spanArr: [], // 一个空的数组，用于存放每一行记录的合并数
      pos: 0, // spanArr 的索引
      contentSpanArr: [],
      position: 0      ,

        isDisable:false,                                                                          //确定键显示按钮
        form: {
          code: '',                                                                      //收货单号 ,
          customerCode: '',                                                                      //客户 ,
          gmtPlanArrival: '',                                                                      //计划到货日期 ,
          groupCode: '',                                                                      //所属机构Code ,
          putawayQuantity: '',                                                                      //上架数量 ,
          receivedQuantity: '',                                                                      //收货数量 ,
          remarks: '',                                                                      //备注 ,
          shipmentCode: '',                                                                      //入驻商 ,
          sourceCode: '',                                                                      //来源单号 ,
          status: '',                                                                      //状态；0:新增；1：作废；2：待收货；3：部分收货；4：收货完成； ,
          supplierCode: '',                                                                      //供应商 ,
          totalQuantity: '',                                                                      //总数量 ,
          type: '',                                                                      //单据类型；0：收货单；1：退货单； ,
          warehouseCode: '',                                                                      //仓库
          receiveItemList: []
        },
        loading: false,
        tableData: [
        ],
        rules: {
          shipmentCode: [
            { required: true, message: '请输入客户姓名', trigger: 'change' }
          ],
          warehouseCode: [
            { required: true, message: '请选择仓库', trigger: 'change' }
          ],
          supplierCode: [
            { required: true, message: '请选择供应商', trigger: 'change' }
          ],
          cancelQuantity: [
            { required: false },
            { pattern: /^[0-9]*[1-9][0-9]*$/, message: '数量必须大于0' },
            { min: 0, message: '数据不能超过18位'}
          ]
        },
        validRules: {
          goodsName: [
            { required: true, message: '商品名称必须填写' },
          ],
          goodsUnit: [
            { required: true, message: '单位必须填写' },
          ],
          planQuantity: [
            { required: true, message: '数量必须填写' },
          ],
        },
        listQuery: {
          page: 1,
          limit: 13,
          totalzong: 0
        },
      }
    },
    computed:{
      typeName(){
        if(this.form.type == '0'){
          return '采购入库'
        }else if(this.form.type == '1'){
          return '客户退货'
        }
      }
    },
    created() {
      this.getWarehouse()
    },
    methods: {
      // 获取页面信息
      getInfo() {
        this.loading = true
        let code = this.$route.query.code ? this.$route.query.code : "";
        receiveCheckIn(code).then(response => {
          this.form = response.data
          if(this.form.type == 0){
            this.isShow0 = true
            this.isShow1 = false
          }
          if(this.form.type == 1){
            this.isShow0 = false
            this.isShow1 = true
          }
          this.tableData = this.form.receiveItemWithRegisterVOList
        this.spanArr = [];
        this.contentSpanArr = [];
        for (var i = 0; i < this.tableData.length; i++) {
          if (i === 0) {
            this.spanArr.push(1);
            this.pos = 0;
            this.contentSpanArr.push(1);
            this.position = 0;
          } else {
            // 判断当前元素与上一个元素是否相同(第1和第2列)
            if (this.tableData[i].goodCode == this.tableData[i - 1].goodCode &&
                this.tableData[i].goodsName == this.tableData[i - 1].goodsName &&
                this.tableData[i].goodsBarCode == this.tableData[i - 1].goodsBarCode &&
                this.tableData[i].goodsUnitName == this.tableData[i - 1].goodsUnitName &&
                this.tableData[i].planQuantity == this.tableData[i - 1].planQuantity
                ) {
              this.spanArr[this.pos] += 1;
              this.spanArr.push(0);
            } else {
              this.spanArr.push(1);
              this.pos = i;
            }

            }
          }
        this.loading = false
      })
      },
      // 收货
      funcReceive(code) {
        this.$refs.editRef.getInfo(code)
        this.modelEditFlag = true
      },

      formatterReceivedQuantity({cellValue}){
        if(cellValue == null){
          return 0
        }else{
          return cellValue
        }
      },

      //选择供应商
      setsupplierCode(value){
        this.form.supplierCode = value.code;
        this.tableData = [];

      },
      // 选择客户
      setCustomerCode(value) {
        this.form.shipmentCode = value;
        this.tableData = [];
      },
      //仓库查询
      getWarehouse(){
        getWarehouse().then(response => {
          this.warehouseData = response.data
          this.getInfo()
        })
      },
      //计算基本单位
      nameChangeEvent (row) {
        console.log(row)
        const sd = row.goodsUnitConversionList.find(i => i.unitName == row.goodsUnitName)
        console.log(sd)
        row.goodsUnit = sd.code
        row.quantity = sd.weight
        row.unitName = sd.unitName
        row.unit = '1' + row.goodsUnitName + '=' + row.quantity + sd.unitName
      },
      //商品选择
      setGoodsCode(row){
        let obj = this.$refs.goodsSelect.obj
        row.goodsName = obj.value
        row.goodsCode = obj.code
        row.goodCode = obj.goodCode
        // row.unitCode = obj.unitCode
        // row.unitName = obj.unitName
        row.goodsBarCode = obj.goodsBarCode
        row.goodsUnitConversionList = obj.goodsUnitConversionList
      },
      // 公共取消
      fatherItemCancel(modelFlag) {
        switch (modelFlag) {
          case 'add':
            this.modelAddFlag = false
            break
          case 'edit':
            this.modelEditFlag = false
            break
          default:
        }
      },
      // 编辑组件的父方法
      fatherEdit() {
        this.modelEditFlag = false
        this.getInfo()
      },

      // 新增
      insertEvent () {
        if (this.form.shipmentCode) {
          const xTable = this.$refs.xTable
          const newRow = {
          }
          xTable.insert().then(({ row }) => xTable.setActiveRow(row))

        } else {
          this.$message.error('入驻商不能为空')
        }

      },
      // 提交
      funcSubmitCheck() {
        this.isDisable = true
        finishReceive(this.form).then(response => {
          this.$message({ message: response.msg, type: 'success' })
          this.$emit('fatherAddMethod')
          this.isDisable = false
        }).then(() => {
          this.tableData = []
          this.form = {}
          this.$eventBus.$emit('refreshList')
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.push({
            path: "/inbound/reciveList"
          });
        }).catch(() => this.isDisable = false)

      },
    // 表格合并行
    objectSpanMethod({ row, rowIndex,column,  columnIndex }) {
      if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4 || columnIndex === 5 ) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },

      footerMethod ({ columns, data }) {
        return [
          columns.map((column, columnIndex) => {
            if (columnIndex === 1) {
              return '合计'
            }
            if (['planQuantity'].includes(column.property)) {
              return this.form.totalQuantity;
            }
            if (['receivedQuantity', 'cancelQuantity'].includes(column.property)) {
                return XEUtils.sum(data, column.property)
            }
            return '-'
          })
        ]
      }
    }
  }
</script>
<style lang="scss" scoped>
  .dialog-footer {
    margin: 150px auto;
    width: 90px;
    // float: right;
  }
</style>

<style>
  .vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
    padding: 6px 0;
  }
  .vxe-toolbar{padding:0 0 10px 0}
</style>
